<template>
  <div>
    <el-tree
      ref="tree"
      :data="permissionData"
      :props="{ label: 'name' }"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />

    <div style="text-align: right;">
      <el-button @click="hCancel">取消</el-button>
      <el-button type="primary" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permisson'
import { tranListToTreeData } from '@/utils/index'
import { getRoleDetail, assignPerm } from '@/api/setting'
export default ({
  props: {
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据

    }
  },
  created() {
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
    this.loadPermissionByRoleId()
  },
  methods: {
    async loadPermissionByRoleId() {
      try {
        const res = await getRoleDetail(this.roleId)
        console.log('获取当前角色的已有的权权限点数据', res.data.permIds)
        // 回填到树上
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (err) {
        console.log(err)
      }
    },
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        console.log(res)
        this.permissionData = tranListToTreeData(res.data)
        console.log(this.permissionData)
      } catch (err) {
        console.log(err)
      }
    },
    hCancel() {
      this.$refs.tree.setCheckedKeys([])
      this.$emit('closeTree')
    },
    async hSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      console.log(res)
      this.$message.success('保存权限成功')
      this.hCancel()
    }
  }
})
</script>
